//事件总线
class EventBus {
  private id = 0
  private eventMap: { [key: string]: { [key: number]: Function } } = {}

  on(eventName: string, handler: Function) {
    if (!this.eventMap[eventName]) {
      this.eventMap[eventName] = {}
    }
    this.eventMap[eventName][++this.id] = handler
    return this.id
  }

  emit(eventName: string, ...rest: any[]) {
    const handlerMap = this.eventMap[eventName] || {}
    Object.values(handlerMap).forEach((handler: Function) => {
      handler(...JSON.parse(JSON.stringify(rest)))
    })
  }

  off(eventName: string | number, handler?: Function) {
    if (typeof eventName === 'number') {
      Object.values(this.eventMap).forEach((handlerMap: { [key: string]: Function }) => {
        Reflect.deleteProperty(handlerMap, eventName)
      })
    } else if (eventName && handler) {
      const handlerMap: { [key: string]: Function } = this.eventMap[eventName] || {}
      Object.keys(handlerMap).forEach((key: string) => {
        if (handlerMap[key] === handler) {
          Reflect.deleteProperty(handlerMap, key)
        }
      })
    } else if (eventName) {
      Reflect.deleteProperty(this.eventMap, eventName)
    }
  }
}

export { EventBus }

export default new EventBus()

// useage

// const handler = (a,b,c) => {}
// const id=bus.on('test', handler)
// bus.emit('test', 1,2,3)
// bus.off(id)//删除指定回调
// bus.off('test', handler)//删除指定回调
// bus.off('test') //删除test所有回调
